﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using SunTzu.Core.Data;

namespace Odyssey.Web.Areas.Admin.Controllers
{
    public class SubclassController : BaseController<tb_subclass>
    {

        private int? ClassId
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["classid"]))
                {
                    return null;
                }
                int classId;
                if (int.TryParse(Request.QueryString["classid"], out classId))
                {
                    return classId;
                }
                return null;
            }
        }

        protected bool IsContent
        {
            get
            {
                return ClassId.GetValueOrDefault() == 2;
            }
        }
        public override ActionResult List(int? page)
        {
            if (ClassId.HasValue)
            {
                ViewData.Model = GetTable<tb_subclass>().Where(item => item.TopClassId == (ClassId ?? 0) && item.isnews == "Y").ToPagedList(page.GetValueOrDefault(), numPerPage);

                return View();
            }
            return base.List(page);
        }

        public override ActionResult Edit(int? id)
        {
            ViewBag.IsNews = ClassId.HasValue && ClassId.Value == 1;
            ViewBag.ParentClasses = GetTable<tb_subclass>().Where(item => item.TopClassId == ClassId && item.parentid == 0);
            return base.Edit(id);
        }

        public ActionResult CascadeList(int? page)
        {
            //加载parentid=0
            ViewBag.Subclasses = GetTable<tb_subclass>().Where(item => item.TopClassId == (ClassId ?? 0) && item.isnews=="N" && item.parentid == 0);
            //加载parentid!=0
            ViewBag.ChildSubclasses = GetTable<tb_subclass>().Where(item => item.TopClassId == (ClassId ?? 0) && item.isnews == "N" && item.parentid != 0).ToList();
            return View();
        }

        public ActionResult CascadeEdit(int? id)
        {
            ViewBag.IsNews = false;
            ViewBag.ParentClasses = GetTable<tb_subclass>().Where(item => item.TopClassId == ClassId && item.parentid == 0 && item.isnews == "N");
            return base.Edit(id);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CascadeSave(int? id)
        {
            return base.Save(id, "CascadeList");
        }

        protected override void BeforeSaveOrUpdate(tb_subclass entity)
        {
            entity.TopClassId = ClassId ?? 0;
            entity.parentid = entity.parentid ?? 0;
            //TODO:创建者，更新者
            //entity.UpdateBy = entity.CreateBy = SessionManager.User.username;
        }
    }
}

